package com.oracle.zebrafreelytraveling.ui.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.oracle.zebrafreelytraveling.R;
import com.oracle.zebrafreelytraveling.data.RequestResult.ResBase;
import com.oracle.zebrafreelytraveling.data.RequestResult.ResFoodInfo;
import com.oracle.zebrafreelytraveling.data.RequestResult.ResViewSpotList;
import com.oracle.zebrafreelytraveling.data.model.ClassifyItem;
import com.oracle.zebrafreelytraveling.data.model.IntroBase;
import com.oracle.zebrafreelytraveling.net.Api;
import com.oracle.zebrafreelytraveling.net.HttpManager;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.CommonAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.base.ViewHolder;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.wrapper.HeaderAndFooterWrapper;
import com.oracle.zebrafreelytraveling.ui.ClassifyFoodActivity;
import com.oracle.zebrafreelytraveling.ui.ClassifyHotelActivity;
import com.oracle.zebrafreelytraveling.ui.MainActivity;
import com.oracle.zebrafreelytraveling.ui.ClassifyTrafficActivity;
import com.oracle.zebrafreelytraveling.ui.ClassifyViewSpotActivity;
import com.oracle.zebrafreelytraveling.ui.view.ClassifyCarouselView;
import com.oracle.zebrafreelytraveling.ui.view.CustomGridLayoutManager;
import com.oracle.zebrafreelytraveling.ui.view.DepthPageTransformer;
import com.oracle.zebrafreelytraveling.utils.ClassInfoUtil;
import com.oracle.zebrafreelytraveling.utils.constant.Constant;
import com.oracle.zebrafreelytraveling.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by yydcnjjw on 2017/7/20.
 * 分类信息fragment
 * 显示 分类的信息
 */

public class ClassifyInfoFragment extends Fragment implements View.OnClickListener {

    private View mView;
    private RecyclerView mClassifyRecycleView;
    private CommonAdapter<ClassifyItem> mCommonAdapter;
    private List<ClassifyItem> mClassifyItemList;
    private ClassifyItem mFoodItem;
    private ClassifyItem mViewItem;
    private List<ResFoodInfo.ResultBean> mFoodInfoList;
    private List<ResViewSpotList.ResultBean> mViewSpotList;
    private HeaderAndFooterWrapper mHFClassifyWrapper;

    private View mHeaderCarouselView;
    private ClassifyCarouselView mCarousel;
    private ImageButton foodBtn;
    private ImageButton viewBtn;
    private ImageButton travelBtn;
    private ImageButton hotelBtn;

    private View mHeaderCityIntroView;
    private SimpleDraweeView mCityImage;
    private TextView mCityName;
    private TextView mCityIntro;

    private String currentCity;
    private Disposable mDisposable;
    private int cityId = 0;

    //控制上拉加载的显隐
    private int page = 0;

    private MainActivity mActivity;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = (MainActivity) activity;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_classify_info, container, false);
        mHeaderCarouselView = LayoutInflater.from(getContext())
                .inflate(R.layout.head_item_classify_carouse, container, false);
        mHeaderCityIntroView = LayoutInflater.from(getContext())
                .inflate(R.layout.head_item_classify_city_info, container, false);
        initView();
        initRecycleView();
        return mView;
    }

    private void initView() {
        mClassifyRecycleView = (android.support.v7.widget.RecyclerView) mView.findViewById(R.id.classify_recycleView);
    }

    private void initRecycleView() {
        mClassifyRecycleView.setLayoutManager(new LinearLayoutManager(getContext()));
        loadClassifyItem();
        mCommonAdapter = new CommonAdapter<ClassifyItem>(getContext(), R.layout.item_classify_list, mClassifyItemList) {
            @Override
            protected void convert(ViewHolder holder, ClassifyItem classifyItem, int position) {
                Button refreshBtn  = holder.getView(R.id.classify_refresh);
                refreshBtn.setOnClickListener(v -> {
                    switch (position) {
                        case Constant.FOOD:
                            loadFoodInfo();
                            break;
                        case Constant.VIEW:
                            loadViewSpotList(cityId);
                            break;
                    }
                });
                Button moreBtn = holder.getView(R.id.classify_more);
                moreBtn.setOnClickListener(v -> {
                    switch (position){
                        case Constant.FOOD:
                            ClassifyFoodActivity.startFoodClassifyActivity(getActivity());
                            break;
                        case Constant.VIEW:
                            ClassifyViewSpotActivity.startViewSpotActivity(getActivity(), cityId);
                            break;
                    }
                });
                CustomGridLayoutManager customGridLayoutManager = new CustomGridLayoutManager(getContext(), 2);
                customGridLayoutManager.setScrollEnabled(false);
                RecyclerView mClassifyInfoGridView = holder.getView(R.id.classify_info_list);
                mClassifyInfoGridView.setLayoutManager(customGridLayoutManager);
                CommonAdapter<Object> mCommonGridAdapter = new CommonAdapter<Object>(getContext(), R.layout.item_classify_type_list, classifyItem.getLabelInfoList()) {
                    @Override
                    protected void convert(ViewHolder holder, Object o, int pos) {
                        switch (position) {
                            case Constant.FOOD:
                                handleFoodType(holder, o);
                                break;
                            case Constant.VIEW:
                                handleViewType(holder, o);
                                break;
                        }
                    }
                };
                mClassifyInfoGridView.setAdapter(mCommonGridAdapter);
                holder.setText(R.id.classify_label, classifyItem.getLabel());
                ProgressBar mProgressBar = holder.getView(R.id.progressBar);
                if (classifyItem.isLoadFinsh()){
                    mProgressBar.setVisibility(View.GONE);
                    holder.getView(R.id.progress_error).setVisibility(View.GONE);
                }
                if (classifyItem.isLoadError()){
                    mProgressBar.setVisibility(View.GONE);
                    holder.getView(R.id.progress_error).setVisibility(View.VISIBLE);
                }
                mCommonGridAdapter.notifyDataSetChanged();
            }
        };
        initCarouselHeader();
        initCityIntroHeader();
        mHFClassifyWrapper = new HeaderAndFooterWrapper(mCommonAdapter);
        mHFClassifyWrapper.addHeaderView(mHeaderCarouselView);
        mHFClassifyWrapper.addHeaderView(mHeaderCityIntroView);
        mClassifyRecycleView.setAdapter(mHFClassifyWrapper);
        loadFoodInfo();
        getCityId();//获取cityId以后加载viewspotlist
    }

    /**
     * 处理美食分类
     */
    private void handleFoodType(ViewHolder holder, Object o) {
        ResFoodInfo.ResultBean foodInfo = (ResFoodInfo.ResultBean) o;
        CardView cardView = holder.getView(R.id.classify_layout);
        cardView.setOnClickListener(v -> {
            IntroBase base = new IntroBase();
            base.setIntroName(foodInfo.getName());
            base.setIntroImage(foodInfo.getPhotos());
            base.setIntroContent(foodInfo.getProduct_rating()+"\n"
                                +foodInfo.getEnvironment_rating()+"\n"
                                +foodInfo.getService_rating());
            base.setIntroLocation(foodInfo.getAddress());
            base.setIntroContact(foodInfo.getPhone());
            base.setLatitude(foodInfo.getLatitude());
            base.setLongitude(foodInfo.getLongitude());
            IntroSlideDialogFragment.newInstance(base, -1).showDialogFragment(getActivity().getFragmentManager());
        });
        SimpleDraweeView foodImage = holder.getView(R.id.classify_image);
        foodImage.setImageURI(foodInfo.getPhotos());
        holder.setText(R.id.classify_name, foodInfo.getName());
    }

    private void handleViewType(ViewHolder holder, Object o) {
        ResViewSpotList.ResultBean viewInfo = (ResViewSpotList.ResultBean) o;
        CardView cardView = holder.getView(R.id.classify_layout);
        IntroBase base = new IntroBase();
        base.setIntroName(viewInfo.getTitle());
        base.setIntroImage(viewInfo.getImgurl());
        base.setIntroLocation(viewInfo.getAddress());
        cardView.setOnClickListener(v -> IntroSlideDialogFragment.newInstance(base, Integer.parseInt(viewInfo.getSid())).showDialogFragment(getActivity().getFragmentManager()));
        SimpleDraweeView viewImage = holder.getView(R.id.classify_image);
        viewImage.setImageURI(viewInfo.getImgurl());
        holder.setText(R.id.classify_name, viewInfo.getTitle());
    }

    private void initCityIntroHeader() {
        mCityImage = (SimpleDraweeView) mHeaderCityIntroView.findViewById(R.id.classify_city_image);
        mCityName = (TextView) mHeaderCityIntroView.findViewById(R.id.classify_city_name);
        mCityIntro = (TextView) mHeaderCityIntroView.findViewById(R.id.classify_city_intro);
    }

    //初始化轮播图
    private void initCarouselHeader() {
        mCarousel = (ClassifyCarouselView) mHeaderCarouselView.findViewById(R.id.carousel_figure_view);
        List<String> list = new ArrayList<>();
        list.add(Constant.DOWNLOAD_URL + "image/cache/1.jpg");
        list.add(Constant.DOWNLOAD_URL + "image/cache/2.jpg");
        list.add(Constant.DOWNLOAD_URL + "image/cache/3.jpg");
        mCarousel.setURL(list);
        mCarousel.setViewPagerSwitchStyle(new DepthPageTransformer());
        mCarousel.setViewPagerSwitchSpeed(500);
        mCarousel.setIndicationPointState(true);
        mCarousel.setCarouselFigureItemClickListener((view, position) -> {
            //TODO 跳转到相应的帖子界面
            ToastUtil.showToast(position+"");
        });

        foodBtn = (ImageButton) mHeaderCarouselView.findViewById(R.id.classify_food);
        viewBtn = (ImageButton) mHeaderCarouselView.findViewById(R.id.classify_view);
        travelBtn = (ImageButton) mHeaderCarouselView.findViewById(R.id.classify_traffic);
        hotelBtn = (ImageButton) mHeaderCarouselView.findViewById(R.id.classify_hotel);

        foodBtn.setOnClickListener(this);
        viewBtn.setOnClickListener(this);
        travelBtn.setOnClickListener(this);
        hotelBtn.setOnClickListener(this);
    }

    /**
     * 加载城市简介信息
     */
    private void loadCityInfo() {

    }

    private void loadFoodInfo() {
        if (TextUtils.isEmpty(currentCity)) {
            //定位失败
            mClassifyItemList.get(Constant.FOOD - 2).setLoadError(true);
            ToastUtil.showToast(getString(R.string.location_false));
            return;
        }
        HttpManager.getInstance().getService(Constant.FOOD_API)
                .getFoodInfoByCity(currentCity, page, Constant.PAGE_SIZE_CLASSIFY)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResFoodInfo>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull ResFoodInfo resFoodInfo) {
                        if (!resFoodInfo.getResultcode().equals(Constant.JUHE_SUCCESS)) {
                            ToastUtil.showToast(getString(R.string.not_any_more));
                            page = 0;
                            mClassifyItemList.get(Constant.FOOD - 2).setLoadError(true);
                            return;
                        }
                        List<ResFoodInfo.ResultBean> list = resFoodInfo.getResult();
                        if (mFoodInfoList != null){
                            mFoodInfoList.addAll(list);
                        }
                    }
                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.d("loadFoodInfoError", e.getMessage());
                        mClassifyItemList.get(Constant.FOOD - 2).setLoadError(true);
                    }

                    @Override
                    public void onComplete() {
                        mHFClassifyWrapper.notifyDataSetChanged();
                    }
                });
        // TODO 模拟数据
        mFoodInfoList.clear();
        mFoodInfoList.addAll(ClassInfoUtil.getFoodList());
        mHFClassifyWrapper.notifyDataSetChanged();
        page++;
    }

    private void getCityId() {
        Api api = HttpManager.getInstance().getService(Constant.BASE_URL);
        Observable<ResBase<Integer>> observable = null;
        if (!TextUtils.isEmpty(currentCity)) {
            observable = api.getCityId(currentCity);
        } else {
            loadViewSpotList(cityId);
            return;
        }
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResBase<Integer>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull ResBase<Integer> integerResBase) {
                        if (integerResBase.getCode().equals(Constant.REQUEST_SUCCESS)){
                            cityId = integerResBase.getData();
                            loadViewSpotList(cityId);
                        }
                        ToastUtil.showToast(integerResBase.getMessage());
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.d("getCityId", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void loadViewSpotList(int cityId){
        Api api = HttpManager.getInstance().getService(Constant.VIEW_API);
        api.getViewSpotList(cityId, page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResViewSpotList>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable = d;
                    }
                    @Override
                    public void onNext(@NonNull ResViewSpotList resViewSpotList) {
                        if (resViewSpotList.getError_code() == 0){
                            mViewSpotList.clear();
                            mViewSpotList.addAll(resViewSpotList.getResult());
                        } else {
                            mClassifyItemList.get(Constant.VIEW - 2).setLoadError(true);
                            ToastUtil.showToast(resViewSpotList.getReason());
                        }
                    }
                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.d("loadViewSpotList", e.getMessage());
                        mClassifyItemList.get(Constant.VIEW - 2).setLoadError(true);
                    }
                    @Override
                    public void onComplete() {
                        mHFClassifyWrapper.notifyDataSetChanged();
                    }
                });
        //// TODO: 2017/8/11 模拟数据
        mViewSpotList.clear();
        mViewSpotList.addAll(ClassInfoUtil.getViewSpotList());
        mHFClassifyWrapper.notifyDataSetChanged();
        page++;
    }


    /**
     * 初始化分类信息 美食 和 景点
     */
    private void loadClassifyItem() {
        mClassifyItemList = new ArrayList<>();
        if (mFoodItem == null){
            mFoodItem = new ClassifyItem();
            mFoodInfoList = new ArrayList<>();
            mFoodItem.setLabel("美食");
            mFoodItem.setLabelInfoList(mFoodInfoList);
        }
        if (mViewItem == null){
            mViewItem = new ClassifyItem();
            mViewSpotList = new ArrayList<>();
            mViewItem.setLabel("景点");
            mViewItem.setLabelInfoList(mViewSpotList);
        }
        mClassifyItemList.add(Constant.FOOD - 2, mFoodItem);
        mClassifyItemList.add(Constant.VIEW - 2, mViewItem);
    }

    public void setCurrentCity(String currentCity) {
        this.currentCity = currentCity;
        if (getUserVisibleHint()){
            loadFoodInfo();
            getCityId();//获取cityId以后加载viewspotlist
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //清除 Disposable
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
        page = 0;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.classify_food:
                ClassifyFoodActivity.startFoodClassifyActivity(getActivity());
                break;
            case R.id.classify_view:
                ClassifyViewSpotActivity.startViewSpotActivity(getActivity(), cityId);
                break;
            case R.id.classify_traffic:
                ClassifyTrafficActivity.startTrafficClassifyActivity(getActivity());
                break;
            case R.id.classify_hotel:
                ClassifyHotelActivity.startHotelActivity(getActivity(), cityId);
                break;
        }
    }
}
